<?php


namespace app\admin\controller\content;

use app\admin\controller\Base;

use app\common\model\ArticleType as models;
use app\common\traites\PublicCrudTrait;
use think\exception\ValidateException;
use \app\validate\ArticleType as validates;

class ArticleType extends Base
{
    protected $model;
    use PublicCrudTrait;

    /**
     * 文章分类控制器
     */
    public function initialize()
    {
        $this->model = new models();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 文章分类
     */
    public function index()
    {
        //当前页
        $page = $this->request->post('page', 1);
        //每页显示数量
        $limit = $this->request->post('limit', 10);
        //查询搜索条件


        $list = $this->model->order('id desc')->paginate(['list_rows'=>$limit,'page'=>$page]);
        return $this->success($list);
    }

    /**
     * 添加
     */
    public function add()
    {
        //过滤数据
        $postField = 'name';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('add')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        $user = $this->model->where('name', $post['name'])->find();
        if ($user) return $this->failed('该分类以存在');

        $save = $this->model->save($post);
        if ($save) return $this->success([]);
        return $this->failed('新增失败');
    }

    /**
     * 菜单查询
     * @return mixed
     */
    public function detail()
    {
        //过滤数据
        $postField = 'id';
        $post = $this->request->only(explode(',', $postField), 'post', null);
        //验证数据
        try {
            validate(validates::class)->scene('detail')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }
        //查询
        $user = $this->model->find($post['id']);
        if ($user) return $this->success($user);
        return $this->failed('分类不存在');
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        //过滤数据
        $postField = 'id,name';
        $post = $this->request->only(explode(',', $postField), 'post', null);

        //验证数据
        try {
            validate(validates::class)->scene('edit')->check($post);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->failed($e->getError());
        }

        //查询是否重复的该菜单
        $find = $this->model->where('name', $post['name'])->where('id', '<>', $post['id'])->find();
        if ($find) return $this->failed('该分类以存在');

        //执行修改数据
        $save = $this->model->update($post);
        if ($save) return $this->success([]);
        return $this->failed('修改失败');
    }
}